﻿using Autofac;
using AutoMapper;
using SIG.Data.Repositories.Case;
using SIG.Data.UnitOfWork;
using SIG.Infrastructure.Cache;
using SIG.Infrastructure.Logging;
using SIG.Service.Case;
using SIG.WebMVC.Mappings;
using System;
using System.Linq;
using System.Reflection;

namespace SIG.WebMVC
{
    public class IoCConfig : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
           
           
            //builder.RegisterType(typeof(SigContext)).As(typeof(DbContext)).InstancePerLifetimeScope();
            builder.RegisterType(typeof(MainBCUnitOfWork)).As(typeof(IMainBCUnitOfWork)).InstancePerRequest();
            builder.RegisterType<LoggingService>().As<ILoggingService>();
            builder.RegisterType<CacheService>().As<ICacheService>();
            builder.RegisterType<Infrastructure.Email.SMTPService>().As<Infrastructure.Email.IEmailService>();

            
            builder.RegisterAssemblyTypes(Assembly.Load("SIG.Data"))
                 .Where(t => t.Name.EndsWith("Repository"))
                 .AsImplementedInterfaces()
                .InstancePerLifetimeScope();
           

            builder.RegisterAssemblyTypes(Assembly.Load("SIG.Service"))
                      .Where(t => t.Name.EndsWith("Service"))
                      .AsImplementedInterfaces()
                      .InstancePerLifetimeScope();
         


            //automapper 注册
            var profiles = from t in typeof(DomainToViewModelMappingProfile).Assembly.GetTypes()  where typeof(Profile).IsAssignableFrom(t) select (Profile)Activator.CreateInstance(t);
            var frontProfiles = from t in typeof(FrontMappingProfile).Assembly.GetTypes() where typeof(Profile).IsAssignableFrom(t) select (Profile)Activator.CreateInstance(t);
            builder.Register(ctx => new MapperConfiguration(cfg =>
            {
                foreach (var profile in profiles)
                {
                    cfg.AddProfile(profile);
                }
            }));
            builder.Register(ctx => new MapperConfiguration(cfg =>
            {
                foreach (var profile in frontProfiles)
                {
                    cfg.AddProfile(profile);
                }
            }));

            builder.Register(ctx => ctx.Resolve<MapperConfiguration>().CreateMapper()).As<IMapper>();

        }
    }
}
